#include <avr/io.h>
#include <stdio.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>

#include "uart.h"
#include "SPI.h"
#include "HEXtoASCII.h"
#include "trf7960.h"

volatile unsigned char RX_to_process;
volatile unsigned char FIFO_num;

void trf7960_init(void)
{
	EICRA = (1<<ISC01)|(1<<ISC00);
	EIMSK = (1<<INT0);
}


void out_regs(void)
{
	unsigned char num = 12;
	
	spi_read_regs(0x00,num);
	
	putchr(13);
	
	for(unsigned char i = 0; i<num; i++)
	{
			hex_to_ascii(i);
			putchr(ascii_hi);
			putchr(ascii_low);
			
			
			putchr(':');
			hex_to_ascii(buf[i]);
			putchr(ascii_hi);
			putchr(ascii_low);
			
		/*	putchr(':');
			hex_to_ascii(default_reg[i]);
			putchr(ascii_hi);
			putchr(ascii_low);
			
			*/
			
			putchr(13);

	}
	
}

void read_fifo(void)
{
	FIFO_num = spi_read_one_reg(0x1C);
	
	FIFO_num = (FIFO_num & 0b00001111)+1;
	
	spi_read_regs(0x1F,FIFO_num);
}


ISR(INT0_vect)
{
	unsigned char temp;
	temp = spi_read_IRQ_status();
//	putchr(13);
	if(bit_is_set(temp,7))
	{
		putchr('T');

	}	

	
	if(bit_is_set(temp,6))
	{
		putchr('R');
		
		
		hex_to_ascii(spi_read_one_reg(0x1C));
		putchr(ascii_hi);
		putchr(ascii_low);
		
		read_fifo();
		for(unsigned char i = 0; i<FIFO_num; i++)
		{
			hex_to_ascii(buf[i]);
			putchr(ascii_hi);
			putchr(ascii_low);
			putchr(' ');

		}
		putchr(13);
		
	/*	if(bit_is_set(temp,5))
		{
			read_fifo();
			RX_to_process = 1;
		}		*/


	}	

	
	if(bit_is_set(temp,5)) putchr('F');

	
	if(bit_is_set(temp,4)) putchr('C');

	
	if(bit_is_set(temp,3)) putchr('P');

	
	if(bit_is_set(temp,2)) putchr('!');

	
	if(bit_is_set(temp,1)) putchr('E');

	
	if(bit_is_set(temp,0)) putchr('N');
	
	putchr(13);
	

	
}

